package com.question.test

import com.question.poi.ParagraphChildOrderManager
import com.spire.doc.Document
import com.spire.doc.FileFormat
import com.spire.doc.documents.ImageType
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions
import org.apache.pdfbox.cos.COSDictionary
import org.apache.pdfbox.pdmodel.PDDocument
import org.apache.pdfbox.pdmodel.common.PDStream
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSignature
import org.apache.pdfbox.rendering.PDFRenderer
import org.apache.poi.ooxml.POIXMLDocument
import org.apache.poi.xwpf.usermodel.XWPFDocument
import org.junit.jupiter.api.Test
import org.slf4j.LoggerFactory
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import javax.imageio.ImageIO

class POITest {

    private val logger = LoggerFactory.getLogger(javaClass)

    private val basePath = "C:\\Users\\51517\\Desktop\\question\\"

    @Test
    fun test() {
        println("this is test")
        logger.info("this is test")
    }

    @Test
    fun readWord() {
        val wordPath = "${basePath}综合基础小练习11.docx"
        val document = XWPFDocument(POIXMLDocument.openPackage(wordPath))
        document.bodyElements[0].let {
            it.body.paragraphs.forEach { paragraph ->
                val text = paragraph.text
                val context = ParagraphChildOrderManager(paragraph).childList
                logger.info("context -> {}", context)
            }
        }
    }

    @Test
    fun transToImage() {
        val wordPath = "${basePath}综合基础小练习11.docx"
        val document = Document().apply { loadFromStream(FileInputStream(File(wordPath)), FileFormat.Auto) }
        val testPath = "/Users/mario/Desktop/question/temp"
        File(testPath).apply {
            if (!this.exists()) this.mkdirs()
        }
        for (i in 0 until document.pageCount) {
            val image = document.saveToImages(i, ImageType.Bitmap)
            val file = File(testPath, "$i.png")
            ImageIO.write(image, "PNG", file)
        }
    }

    @Test
    fun transToPdf() {
        val wordPath = "${basePath}综合基础小练习11.docx"
        val document = XWPFDocument(POIXMLDocument.openPackage(wordPath))
        val pdfOptions = PdfOptions.create()
        val testPath = "${basePath}temp"
        FileOutputStream(File(testPath, "test.pdf")).use { outStream ->
            PdfConverter.getInstance().convert(document, outStream, pdfOptions)
        }
    }

    @Test
    fun transToPdf2() {
        val wordPath = "${basePath}综合基础小练习11 - 副本.docx"
        val document = Document().apply { loadFromStream(FileInputStream(File(wordPath)), FileFormat.Auto) }
        val testPath = File("${basePath}temp").apply { if (!exists()) mkdirs() }
        document.saveToFile("$testPath\\test1.pdf", FileFormat.PDF)
    }

    @Test
    fun pdfToImage() {
        val pdfPath = "${basePath}temp\\test1.pdf"
        val testPath = "${basePath}temp"
        val pdfDoc = PDDocument.load(File(pdfPath))
        pdfDoc.document.objects.forEach {
            logger.info("it -> {}",it)
        }
        val pdfRenderer = PDFRenderer(pdfDoc)
        pdfDoc.pages.forEachIndexed { index, page ->
            page.mediaBox.cosArray.forEach {
                logger.info("it -> {}", it)
            }
            page.contentStreams.forEach {
                val list = it.decodeParms
                logger.info("list {}", list)
            }
            val image = pdfRenderer.renderImage(index)
            ImageIO.write(image, "PNG", File(testPath, "FromPDF_$index.png"))
        }
    }

    @Test
    fun sizeTest() {
        val wordPath = "${basePath}综合基础小练习11.docx"
        val document = XWPFDocument(POIXMLDocument.openPackage(wordPath))
//        document.bodyElements.forEach {
//            it.body.paragraphs.forEach { xwpfParagraph ->
//                val ph = xwpfParagraph.ctpPr.sectPr.pgSz.h
//                logger.info("ph:{}", ph)
//            }
//        }
        document.document.body.sectPr.apply {
            val pageSize = pgSz.h
            val topSize = pgMar.top
            val bottomSize = pgMar.bottom
            logger.info("pageSize:{}", pageSize)
            logger.info("topSize:{}", topSize)
            logger.info("bottomSize:{}", bottomSize)
        }
    }

    @Test
    fun heightTest() {
        val wordPath = "${basePath}temp\\myTest.docx"
        // 创建 document 对象
        val wordDoc = XWPFDocument()
        wordDoc.createParagraph().apply {
            createRun().setText("just is test")
        }
        wordDoc.createEndnote()
        FileOutputStream(wordPath).use {
            wordDoc.write(it)
        }
        Thread.sleep(500)
        val document = XWPFDocument(POIXMLDocument.openPackage(wordPath))
        document.document.body.sectPr.apply {
            val pageSize = pgSz.h
            val topSize = pgMar.top
            val bottomSize = pgMar.bottom
            logger.info("pageSize:{}", pageSize)
            logger.info("topSize:{}", topSize)
            logger.info("bottomSize:{}", bottomSize)
        }
    }

    @Test
    fun genHtml() {
        val wordPath = "${basePath}综合基础小练习11.docx"
        val testPath = "${basePath}temp\\"
        val document = Document().apply { loadFromStream(FileInputStream(File(wordPath)), FileFormat.Auto) }
        document.saveToFile("${testPath}11111.pdf", FileFormat.PDF)
    }

    @Test
    fun genImageTest() {
        val wordPath = "${basePath}temp\\myTest.docx"
        // 创建 document 对象
        val wordDoc = XWPFDocument()
        wordDoc.createParagraph().apply {
            createRun().setText("just is test")
        }
        wordDoc.createEndnote()
        wordDoc.document.body.sectPr.apply {
            val pageSize = pgSz.h
            val topSize = pgMar.top
            val bottomSize = pgMar.bottom
            logger.info("pageSize:{}", pageSize)
            logger.info("topSize:{}", topSize)
            logger.info("bottomSize:{}", bottomSize)
        }

        val wordStream = ByteArrayOutputStream().apply { wordDoc.write(this) }
        var byteArray: ByteArray?
        wordStream.use { byteArray = it.toByteArray() }

        // 使用 document 创建 PDF 对象
        byteArray ?: return
        val doc = Document().apply { loadFromStream(ByteArrayInputStream(byteArray), FileFormat.Auto) }
        val pdfArray: ByteArray = ByteArrayOutputStream().use {
            doc.saveToStream(it, FileFormat.Html)
            it.toByteArray()
        }

        // pdf 写入图片
        val pdfDoc = PDDocument.load(pdfArray)
        val pdfRenderer = PDFRenderer(pdfDoc)
        val testPath = "${basePath}temp"
        pdfDoc.pages.forEachIndexed { i, p ->
            val height = p.mediaBox.height
            val image = pdfRenderer.renderImage(i)
            ImageIO.write(image, "PNG", File(testPath, "GenPDF_$i.png"))
        }
//        FileOutputStream(wordPath).use {
//            document.write(it)
//        }
    }
}